<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getList, add, update, deleteByIds } from "@/api/system/course-category";
import type { CourseCategory, CourseCategoryListVO } from "@/api/system/course-category/type";

defineOptions({
  name: "CourseCategory",
});

const tableData = ref<CourseCategoryListVO[]>([]);
const dialogVisible = ref(false);
const dialogTitle = ref("");
const loading = ref(false);
const expandedRowKeys = ref<string[]>([]);
const formData = ref<Partial<CourseCategory>>({
  id: 0,
  name: "",
  parentId: 0,
});

// 获取列表数据
const fetchData = async () => {
  loading.value = true;
  try {
    const res = await getList();
    // 确保每个分类都有 children 数组
    tableData.value = res.map((item) => ({
      ...item,
      children: item.children || [],
    }));
    // 默认展开第一项
    if (tableData.value.length > 0) {
      expandedRowKeys.value = [tableData.value[0].id.toString()];
    }
  } catch (error) {
  } finally {
    loading.value = false;
  }
};

// 处理展开行变化
const handleExpandChange = (row: CourseCategoryListVO) => {
  const rowId = row.id.toString();
  if (expandedRowKeys.value.includes(rowId)) {
    expandedRowKeys.value = [];
  } else {
    expandedRowKeys.value = [rowId];
  }
};

// 打开新增/编辑对话框
const handleDialog = (row?: CourseCategory, isSubCategory: boolean = false) => {
  if (row) {
    if (isSubCategory) {
      dialogTitle.value = "新增子分类";
      formData.value = {
        name: "",
        parentId: row.id,
      };
    } else {
      dialogTitle.value = "编辑分类";
      formData.value = {
        id: row.id,
        name: row.name,
        parentId: row.parentId,
      };
    }
  } else {
    dialogTitle.value = "新增分类";
    formData.value = {
      name: "",
      parentId: 0,
    };
  }
  dialogVisible.value = true;
};

// 保存数据
const handleSave = async () => {
  try {
    if (formData.value.id) {
      await update(formData.value as CourseCategory);
      ElMessage.success("更新成功");
    } else {
      await add(formData.value as CourseCategory);
      ElMessage.success("新增成功");
    }
    dialogVisible.value = false;
    await fetchData();
  } catch (error) {}
};

// 删除数据
const handleDelete = async (row: CourseCategory) => {
  try {
    await ElMessageBox.confirm("确认删除该分类吗？", "提示", {
      type: "warning",
    });
    await deleteByIds(row.id.toString());
    ElMessage.success("删除成功");
    await fetchData();
  } catch (error) {
    if (error !== "cancel") {
    }
  }
};

onMounted(() => {
  fetchData();
});
</script>

<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>课程分类管理</span>
          <el-button type="primary" @click="handleDialog()">新增分类</el-button>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="tableData"
        row-key="id"
        border
        style="width: 100%"
        :expand-row-keys="expandedRowKeys"
        @expand-change="handleExpandChange"
      >
        <el-table-column type="expand" width="50">
          <template #default="{ row }">
            <div class="sub-table-container">
              <el-table
                v-if="row.children && row.children.length > 0"
                v-loading="loading"
                :data="row.children"
                style="width: 95%"
                class="sub-table"
              >
                <el-table-column prop="name" label="子分类名称" />
                <el-table-column prop="createTime" label="创建时间" width="180" />
                <el-table-column prop="updateTime" label="更新时间" width="180" />
                <el-table-column label="操作" width="200">
                  <template #default="{ row: childRow }">
                    <el-button type="primary" link @click="handleDialog(childRow)">编辑</el-button>
                    <el-button type="danger" link @click="handleDelete(childRow)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div v-else class="empty-text">暂无子分类</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="分类名称" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column label="操作" width="300">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleDialog(row)">编辑</el-button>
            <el-button type="success" link @click="handleDialog(row, true)">添加子分类</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="formData" label-width="80px">
        <el-form-item label="分类名称">
          <el-input v-model="formData.name" placeholder="请输入分类名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .sub-table-container {
    padding: 10px 0;
    background-color: #fafafa;
  }

  .sub-table {
    margin-left: 20px;
    width: 95%;
    background-color: #fff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .empty-text {
    text-align: center;
    color: #909399;
    padding: 10px 0;
  }
}
</style>
